<template>
    <div class="knowledge-container">
        <!-- 工具栏 -->
        <div class="toolbar">
            <el-input v-model="searchQuery" placeholder="请输入标题搜索" style="width: 250px;" @keyup.enter="handleSearch">
                <template #append>
                    <el-button icon="Search" @click="handleSearch" />
                </template>
            </el-input>
            <el-button type="primary" @click="openAddDialog" icon="Plus">新增条目</el-button>
        </div>

        <!-- 表格 -->
        <el-table :data="filteredKnowledges" border stripe style="width: 100%; margin-top: 20px;" :loading="loading">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="title" label="标题" width="200"></el-table-column>
            <el-table-column prop="content" label="内容" min-width="300">
                <template #default="{ row }">
                    <span class="table-content" :title="row.content">{{ row.content }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="160" align="center"></el-table-column>
            <el-table-column prop="updatedAt" label="更新时间" width="160" align="center"></el-table-column>
            <el-table-column label="操作" width="150" align="center">
                <template #default="{ row }">
                    <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteKnowledge(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" :current-page="currentPage"
            @current-change="handlePageChange" style="margin-top: 20px; text-align: center;"></el-pagination>

        <!-- 新增/编辑弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" @close="resetForm" width="60%">
            <el-form :model="form" ref="formRef" label-width="120px" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="标题" prop="title">
                            <el-input v-model="form.title" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="内容" prop="content">
                            <el-input v-model="form.content" type="textarea" :rows="6" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';

// 数据相关变量
const knowledges = ref([]);
const searchQuery = ref('');
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);

// 弹窗相关变量
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = reactive({
    id: null,
    title: '',
    content: ''
});

// 表单验证规则（示例）
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ]
};

// 获取知识库列表
const fetchKnowledges = async (pageNum, pageSize) => {
    loading.value = true;
    try {
        const response = await request.get(`/knowledge/list?pageNum=${pageNum}&pageSize=${pageSize}`);
        knowledges.value = response.data.records;
        total.value = response.data.total;
    } catch (error) {
        console.error('获取知识库列表失败:', error);
    } finally {
        loading.value = false;
    }
};

// 计算属性：过滤后的知识库列表
const filteredKnowledges = computed(() => {
    return (knowledges.value || []).filter(knowledge =>
        knowledge?.title?.includes(searchQuery.value)
    );
});

onMounted(() => {
    fetchKnowledges(currentPage.value, pageSize.value);
});

// 搜索处理函数
const handleSearch = () => {
    currentPage.value = 1;
    fetchKnowledges(currentPage.value, pageSize.value);
};

// 分页处理函数
const handlePageChange = (newPage) => {
    currentPage.value = newPage;
    fetchKnowledges(newPage, pageSize.value);
};

// 打开新增对话框
const openAddDialog = () => {
    isEdit.value = false;
    dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
    isEdit.value = true;
    Object.assign(form, row);
    dialogVisible.value = true;
};

// 提交表单（新增或编辑）
const submitForm = async () => {
    try {
        if (!isEdit.value) {
            await request.post('/knowledge', form);
        } else {
            await request.put('/knowledge', form);
        }
        ElMessage.success(isEdit.value ? '编辑成功' : '新增成功');
        dialogVisible.value = false;
        resetForm();
        fetchKnowledges(currentPage.value, pageSize.value);
    } catch (error) {
        console.error('提交表单失败:', error);
        ElMessage.error('操作失败');
    }
};

// 删除知识库条目
const deleteKnowledge = async (id) => {
    try {
        await request.delete(`/knowledge/${id}`);
        ElMessage.success('删除成功');
        fetchKnowledges(currentPage.value, pageSize.value);
    } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败');
    }
};

// 重置表单
const resetForm = () => {
    form.id = null;
    form.title = '';
    form.content = '';
};

// 弹窗标题计算属性
const dialogTitle = computed(() => {
    return isEdit.value ? '编辑知识条目' : '新增知识条目';
});
</script>

<style lang="scss" scoped>
.knowledge-container {
    padding: 20px;
    background-color: #f9f9f9;
}

.toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;
}

.table-content {
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 500px;
}
</style>